/**
 * @author hanzhichen
 * @date 2021-01-25
 * echart显示的公共组件, 接收前后端的echart配置, 生成完整的echarts配置.
 */
import React, {useEffect, useRef} from 'react';
import {Empty} from 'antd';
import echarts from 'echarts';
import {useMount, useUpdateEffect} from 'ahooks';
import {mergeEchartsOption} from '../../utils/convert';
import './index.styl';

const CommonEchart = props => {
    const {
        dataSource: {chart, config} = {},
        id = 'ErrorCommonChartId',
        onDrilling,
        extendEchartsOptions,
        height = 350
    } = props;
    const options = chart;
    const myChart = useRef({});
    const {series = []} = chart || {};
    const seriesData = series.every(ele => !ele?.data?.length > 0);

    const handleEchart = () => {
        myChart.current = echarts.init(document.getElementById(id));
        if (series?.length && !seriesData) {
            if (options) {
                const pieOptions = mergeEchartsOption(
                    options,
                    extendEchartsOptions
                );
                myChart?.current?.setOption(pieOptions, true);
                myChart.current.off('click');
                myChart.current.on('click', params => {
                    if (config?.drilling === 0) {
                        return;
                    }
                    typeof onDrilling === 'function' &&
                        onDrilling({
                            info: params
                        });
                });
            }
        }
        else {
            echarts.init(document.getElementById(id)).dispose();
        }
    };

    useMount(() => {
        handleEchart();
    }, []);

    useUpdateEffect(() => {
        handleEchart();
    }, [options]);
    return (
        <>
            <div
                className="echart-card-content"
                id={id} style={(series?.length && !seriesData) ? {height} : {display: 'none'}}
            />
            {
                (series?.length && !seriesData) ? null : <div className="echart-not-data"><Empty /></div>
            }
        </>
    );
};

export default CommonEchart;
